//
//  UIImage+Base64.m
//  TSWebKit_Example
//
//  Created by 杨志 on 2020/10/30.
//  Copyright © 2020 Reachstar. All rights reserved.
//

#import "UIImage+Base64.h"

@implementation UIImage (Base64)

- (NSString *)base64String {
    NSData *imageData = nil;
    NSString *mimeType = nil;
    NSString *suffix = nil ;
//    if ([self imageHasAlpha]) {
        imageData = UIImagePNGRepresentation(self);
        mimeType = @"image/png";
        suffix = @".png" ;
//    } else {
//        imageData = UIImageJPEGRepresentation(self, 0.5f);
//        mimeType = @"image/jpeg";
//        suffix = @".jpeg" ;
//    }
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] ;
    NSString *fileName = [filePath stringByAppendingFormat:@"/temp%@", suffix] ;
    [imageData writeToFile:fileName atomically:YES] ;
    NSData *data = [NSData dataWithContentsOfFile:fileName] ;
    NSString *base64String = [NSString stringWithFormat:@"data:%@;base64,%@", mimeType,
            [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
    NSFileManager *fileManager = [NSFileManager defaultManager] ;
    if ([fileManager fileExistsAtPath:fileName]) {
        [fileManager removeItemAtPath:filePath error:nil] ;
    }
    //+号必须替换为%2B，要不然同样会失败!
    base64String = [base64String stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"] ;
    return base64String ;
}

@end
